package com.ds.esd.localproxy.handler.dsm;

import com.alibaba.fastjson.JSONObject;
import com.ds.config.ErrorResultModel;
import com.ds.esd.localproxy.handler.AbstractRADHandler;
import com.ds.server.httpproxy.core.Handler;
import com.ds.server.httpproxy.core.HttpRequest;
import com.ds.server.httpproxy.core.HttpResponse;
import com.ds.server.httpproxy.core.Server;
import com.ds.web.RequestMethodBean;

import java.io.IOException;
import java.util.logging.Logger;
import java.util.regex.Pattern;


public class DYNMethodHandler extends AbstractRADHandler implements Handler {
    private static final Logger log = Logger.getLogger(com.ds.server.httpproxy.handler.ResourceHandler.class.getName());

    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {

        boolean ruleMatches = rule.matcher(request.getUrl()).matches();
        if (!ruleMatches) {
            return false;
        }
        log.info("request url " + request.getUrl());
        RequestMethodBean methodBean = this.getRequestMethodBean(request);
        if (methodBean == null) {
            return false;
        }

        try {
            Object object = this.invokMethod(methodBean, request, response);
            String json = object.toString();
            if (json.endsWith(".ftl")) {
                return this.sendFtl(request, response, json);
            } else {
                if (methodBean.getResponseBody() != null) {
                    json = JSONObject.toJSONString(object);
                }
                return sendJSON(methodBean, response, json);
            }


        } catch (Exception e) {
            e.printStackTrace();
            ErrorResultModel resultModel = new ErrorResultModel();
            resultModel.setErrdes(e.getMessage());
            return sendJSON(methodBean, response, JSONObject.toJSONString(resultModel, false));
        }

    }

}
